import base64
import pickle

from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response

from carts import constants
from carts.serializer import CartSerializer, CartSKUSerializer
from goods.models import SKU
from meiduo_mall.utils.DBHelper import create_redis_conn

class CartView(APIView):
    def perform_authentication(self, request):
        # 重写该方法是验证跳过JWT
        pass

    def post(self, request):
        print(request.data)
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 验证成功保存到数据库中
        sku_id = request.data['sku_id']
        count = request.data['count']
        selected = request.data.get('selected', False)

        # 获取当前用户
        try:
            user = request.user
        except Exception as e:
            user = None
        if user and user.is_authenticated:
            redis_conn = create_redis_conn('cart')
            # 对于保存的数据用户勾选和未勾选
            # 创建管道，使用哈希
            pl = redis_conn.pipeline()
            cart_key = 'cart_%s' % user.id
            pl.hincrby(cart_key, sku_id, count)
            cart_selected_key = 'cart_selected_%s' % user.id
        # 设置cookie
            if selected:
                pl.sadd(cart_selected_key, sku_id)
            pl.execute()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            cookie_cart = request.COOKIES.get('cart')
            if cookie_cart:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart))
            else:
                cart_dict = {}
            if sku_id in cart_dict:
                count += cart_dict[sku_id]['count']
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }
            cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()
            response = Response(serializer.data, status=status.HTTP_201_CREATED)
            response.set_cookie('cart', cart_data, max_age=constants.CART_COOKIE_EXPIRES)
        return response

    def get(self, request):
        try:
            user = request.user
        except Exception as e:
            user = None

        if user and user.is_authenticated:
            redis_conn = create_redis_conn('cart')
            # 获取哈希列表中的数据
            cart_key_all = redis_conn.hgetall('cart_%s' % user.id)
            print(cart_key_all)
            # 获取set集合中的数据
            cart_selected_key = redis_conn.smembers('cart_selected_%s' % user.id)
            cart_dict = {}
            for sku_id, count in cart_key_all.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected_key
                }
        else:
            cookie_cart = request.COOKIES.get('cart')
            if cookie_cart:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart))
            else:
                cart_dict = {}
        skus = SKU.objects.filter(id__in=cart_dict.keys())
        for sku in skus:
            sku.count = cart_dict[sku.id]['count']
            sku.selected = cart_dict[sku.id]['selected']
        serializer = CartSKUSerializer(skus, many=True)
        return Response(serializer.data)
